package com.sgb.kjwl.view.widget.pick;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;
import com.sgb.kjwl.R;
import com.swgk.core.dialog.BaseBottomDialog;
import com.swgk.core.dialog.DialogViewHolder;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.qrcode.QRCodeUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import cn.sharesdk.dingding.friends.Dingding;
import cn.sharesdk.dingding.utils.DingdingClientNotExistException;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;

public class PickAuctionShareDialog extends BaseBottomDialog {

    private Platform platform;
    private String title;//标题
    private String url;//分享url
    private String textContext;//分享文本
    private final String imageurl;//商品图url
    private final String onevalues;//一级内容
    private final String twovalues;//二及内容
    private int type;//类型：1、拍卖
    private Activity activity;
    private DialogClickCallBack dialogClickCallBack;
    private TextView names;
    private TextView onekey;
    private TextView onevalue;
    private TextView twokey;
    private TextView twovalue;
    private ImageView iv_qr_code;//二维码
    private ImageView imageview;//商品图
    private int states;//1、待拍卖  2、拍卖中 3拍卖结束
    private int versions;//竞买次数

    public PickAuctionShareDialog (String title, String url, String textContext, String imageurl,String onevalues, String twovalues ,int type,Activity activity,int state,int version, DialogCallBack dialogCallBack) {
        super(activity,dialogCallBack);
        this.title = title;
        this.url = url;
        this.textContext = textContext;
        this.type = type;
        this.activity = activity;
        this.imageurl = imageurl;
        this.onevalues = onevalues;
        this.twovalues = twovalues;
        this.states = state;
        this.versions = version;
        initData();
    }

    private void initData(){
        if (type == 1) {//拍卖
            names.setText(title+"");
            names.setTextColor(context.getResources().getColor(R.color.color_tab_one));
            onekey.setText("地址：");
            onekey.setTextColor(context.getResources().getColor(R.color.color_tab_two));
            onevalue.setText(onevalues+"");
            onevalue.setTextColor(context.getResources().getColor(R.color.color_tab_one));
            switch (states){
                case 1:
                    twokey.setText("起拍价：");
                    break;
                case 2:
                    if (versions>0){
                        twokey.setText("当前价：");
                    }else {
                        twokey.setText("起拍价：");
                    }
                    break;
                case 3:
                    twokey.setText("成交价：");
                    break;
            }
            twokey.setTextColor(context.getResources().getColor(R.color.color_tab_two));
            twovalue.setText(twovalues+"");
            twovalue.setTextColor(context.getResources().getColor(R.color.color_shopping_car_price));
            Glide.with(context).load(imageurl).into(imageview);
        }
        iv_qr_code.setImageBitmap(QRCodeUtils.createQRCode(url, ResolutionUtil.dp2px(getContext(), 61),ResolutionUtil.dp2px(getContext(), 61),true));
    }

    @Override
    protected int dialogLayout() {
        return R.layout.pick_share_dialog_auction;
    }

    @Override
    protected void initView(DialogViewHolder holder, Bundle savedInstanceState) {

        imageview = holder.getDialog().findViewById(R.id.imageview);
        names = holder.getDialog().findViewById(R.id.name);
        onekey = holder.getDialog().findViewById(R.id.one_key);
        onevalue = holder.getDialog().findViewById(R.id.one_value);
        twokey = holder.getDialog().findViewById(R.id.two_key);
        twovalue = holder.getDialog().findViewById(R.id.two_value);
        iv_qr_code = holder.getDialog().findViewById(R.id.iv_qr_code);

        holder.getDialog().findViewById(R.id.tv_dingding).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareSDKContent(2);
            }
        });
        holder.getDialog().findViewById(R.id.tv_wechat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareSDKContent(0);
            }
        });
        holder.getDialog().findViewById(R.id.tv_wechat_moments).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareSDKContent(1);
            }
        });
        holder.getDialog().findViewById(R.id.tv_qq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareSDKContent(3);
            }
        });
        holder.getDialog().findViewById(R.id.tv_copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", url);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                MToast.showToast(getContext(), "复制链接成功！");
                dismiss();
            }
        });
        holder.getDialog().findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean hasPermission = EsayPermissions.isHasPermission(getContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (hasPermission) {
                    saveBitmapFromView(holder.getDialog().findViewById(R.id.pic_layout));
                } else {
                    EsayPermissions.with(activity).permission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE).request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            saveBitmapFromView(holder.getDialog().findViewById(R.id.pic_layout));
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            if (dialogClickCallBack != null){
                                dialogClickCallBack.onItemClick("存储权限未开启 !");
                            }
                        }
                    });
                }
            }
        });
        holder.getDialog().findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        holder.getDialog().findViewById(R.id.rel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    private void ShareSDKContent(int flag) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(textContext);
        sp.setImageUrl(imageurl);
        sp.setUrl(url);
        sp.setTitleUrl(url);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        switch (flag) {
            case 0:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                break;
            case 1:
                platform = ShareSDK.getPlatform(WechatMoments.NAME);
                break;
            case 2:
                platform = ShareSDK.getPlatform(Dingding.NAME);
                break;
            case 3:
                platform = ShareSDK.getPlatform(QQ.NAME);
                break;
        }

        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                dialogClickCallBack.onItemClick("分享成功！");
                dismiss();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                if (throwable instanceof WechatClientNotExistException) {
                    dialogClickCallBack.onItemClick("微信未安装！");
                }
                if (throwable instanceof DingdingClientNotExistException) {
                    dialogClickCallBack.onItemClick("钉钉未安装！");
                }
                if ("QQClientNotExistException".equals(throwable.getMessage())) {
                    dialogClickCallBack.onItemClick("QQ未安装！");
                }
                dismiss();
            }

            @Override
            public void onCancel(Platform platform, int i) {
                dialogClickCallBack.onItemClick("分享取消！");
                dismiss();
            }
        });
        platform.share(sp);
    }


    public void saveBitmapFromView(View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        view.draw(c);
        saveImageToGallery(bmp, title + ".jpeg");
    }

    public void saveImageToGallery(Bitmap bitmap, String bitName) {
        String storePath =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/SGB/";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(storePath, bitName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(
                        this.getContext().getContentResolver(),
                        file.getAbsolutePath(),
                        bitName,
                        null
                );
                MToast.showToast(getContext(), "保存图片成功！");
                dismiss();
            } else {
                MToast.showToast(getContext(), "保存图片失败！");
            }
        } catch (Exception e) {
            MToast.showToast(getContext(), "保存图片失败！");
            e.printStackTrace();
        }
    }

    public interface DialogClickCallBack {
        void onItemClick(String name);
    }

    public PickAuctionShareDialog setDialogClickCallBack(DialogClickCallBack dialogClickCallBack) {
        this.dialogClickCallBack = dialogClickCallBack;
        return this;
    }
}
